<?php

namespace App\Services\Impl;

use App\Services\IWeixinService;
use Cache;
use Log;

class WeixinServiceImpl implements IWeixinService {

    private $appId;
    private $appSecret;

    public function __construct() {
        $this->appId = config('services.WeixinAppID');
        $this->appSecret = config('services.WeixinAppSecret');
    }

    public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();

        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode($this->get_php_file("jsapi_ticket.php") ?: '{"jsapi_ticket":"","expire_time":0}');
        if ($data->expire_time < time()) {
            $accessToken = $this->getAccessToken();
            // 如果是企业号用以下 URL 获取 ticket
            $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            //$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $this->set_php_file("jsapi_ticket.php", json_encode($data));
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }

        return $ticket;
    }

    private function getAccessToken() {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode($this->get_php_file("access_token.php") ?: '{"access_token":"","expire_time":0}');
        if ($data->expire_time < time()) {
            // 如果是企业号用以下URL获取access_token
            $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
            //$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $this->set_php_file("access_token.php", json_encode($data));
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    private function httpMultiGet(array $urls) {
        return curl_multi($urls,[
            CURLOPT_RETURNTRANSFER=>true,
            CURLOPT_TIMEOUT=>500,
            CURLOPT_SSL_VERIFYPEER=>true,
            CURLOPT_SSL_VERIFYHOST=>true
        ]);
//        $res = [];
//        foreach ($urls as $url){
//            $curl = curl_init();
//            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//            curl_setopt($curl, CURLOPT_TIMEOUT, 500);
//            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
//            @curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
//            curl_setopt($curl, CURLOPT_URL, $url);
//
//            $res[] = curl_exec($curl);
//            curl_close($curl);
//        }
//        return $res;
    }

    private function httpPost($url,array $post = []) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        @curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post));

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        @curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }

    private function get_php_file($filename) {
        return trim(Cache::store('file')->get($filename));
    }

    private function set_php_file($filename, $content) {
        Cache::store('file')->put($filename, $content, 9999999999);
    }

    public function getUserAuthorize($redirect_uri, $successState) {
        $redirect_uri = urlencode(urldecode($redirect_uri));
        $authorizeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appId}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state={$successState}#wechat_redirect";
        return redirect($authorizeUrl);
        //员工点击后，页面将跳转至 redirect_uri?code=CODE&state=STATE，企业可根据code参数获得员工的userid。
    }
    
    public function getUserinfoAuthorize($redirect_uri, $successState){
        $redirect_uri = urlencode(urldecode($redirect_uri));
        $authorizeUrl = "https://qy.weixin.qq.com/cgi-bin/loginpage?corp_id={$this->appId}&redirect_uri={$redirect_uri}&state={$successState}&usertype=all";
        return redirect($authorizeUrl);
        //授权流程完成后，会进入回调URI，并在URL参数中返回授权码(redirect_url?auth_code=xxx)
    }
    
    public function getUserinfo($auth_code) {
        $ACCESS_TOKEN = $this->getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_login_info?access_token={$ACCESS_TOKEN}";
        $res = json_decode($this->httpPost($url,[
            'auth_code'=>$auth_code
        ]));
        return $res;
//        c) 登录用户为企业号成员时返回如下：
//        {
//            "usertype": 5,
//            "user_info":{
//                "userid":"xxxx",
//                "name":"xxxx",
//                "avatar":"xxxx"
//            },
//            "corp_info":{
//                "corpid":"wx6c698d13f7a409a4",
//            }
//        }
    }

    /**
     * 根据code获取成员
     * @param type $code
     * @return array
     */
    public function getUser($code) {
        $ACCESS_TOKEN = $this->getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$ACCESS_TOKEN}&code={$code}";
        return json_decode($this->httpGet($url));
//        a)企业成员授权时返回示例如下：
//        {
//            "UserId":"USERID",
//            "DeviceId":"DEVICEID"
//        }
//        b)非企业成员授权时返回示例如下：
//        {
//            "OpenId":"OPENID",
//            "DeviceId":"DEVICEID"
//        }
    }

    /**
     * userid转换成openid
     * @param type $userid
     * @return string
     */
    public function useridToOpenid($userid) {
        $ACCESS_TOKEN = $this->getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token={$ACCESS_TOKEN}";
        $res = json_decode($this->httpPost($url,[
            'userid'=>$userid
        ]));
        return !empty($res->openid) ? $res->openid : null;
//        {
//            "errcode": 0,
//            "errmsg": "ok",
//            企业号成员userid对应的openid，若有传参agentid，则是针对该agentid的openid。否则是针对企业号corpid的openid
//            "openid": "oDOGms-6yCnGrRovBj2yHij5JL6E",
//            应用的appid，若请求包中不包含agentid则不返回appid。该appid在使用微信红包时会用到
//            "appid":"wxf874e15f78cc84a7"
//        }
    }
    
    /**
     * openid转换成userid
     * @param type $openid
     * @return string
     */
    public function openidToUserid($openid) {
        $ACCESS_TOKEN = $this->getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid?access_token={$ACCESS_TOKEN}";
        $res = json_decode($this->httpPost($url,[
            'openid'=>$openid
        ]));
        return !empty($res->userid) ? $res->userid : null;
//        {
//            "errcode": 0,
//            "errmsg": "ok",
//            该openid在企业号中对应的成员userid
//            "userid": "zhangsan"
//        }
    }

    public function getMedia(array $media_ids)
    {
        $ACCESS_TOKEN = $this->getAccessToken();
        $urls = [];
        foreach ($media_ids as $media_id){
            if (!empty($media_id)){
                $urls[] = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token={$ACCESS_TOKEN}&media_id={$media_id}";
            }else{
                $urls[] = null;
            }
        }
        $res = $this->httpMultiGet($urls);
        foreach ($res as $k=>$tmp){
            if (!empty($tmp) && (strlen($tmp) < 50) && strpos($tmp,'errcode')){
                $res[$k] = null;
                Log::notice($tmp,[$urls[$k]]);
            }
        }
        return $res;
//        返回结果：和普通的http下载相同，请根据http头做相应的处理
//        a)正确时返回：
//
//        {
//            HTTP/1.1 200 OK
//           Connection: close
//           Content-Type: image/jpeg
//           Content-disposition: attachment; filename="MEDIA_ID.jpg"
//           Date: Sun, 06 Jan 2013 10:20:18 GMT
//           Cache-Control: no-cache, must-revalidate
//           Content-Length: 339721
//
//           Xxxx
//        }
//        b)错误时返回（这里省略了HTTP首部）：
//
//        {
//            "errcode": "40004",
//           "errmsg": "invalid media_id"
//        }
    }


}
